package com.technician.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.technician.model.security.LoginUser;
import com.technician.utils.JwtUtil;
import com.technician.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 获取 token
        String token = httpServletRequest.getHeader("token");
        // 验证是否携带 token
        if (StringUtils.isBlank(token)) {
            // 没有携带 token , 放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        // 携带了 token , 解析 token 获得 userId 再从 redis 获取 LoginUser
        String userId = null;
        try {
            // 解析 token
            Claims claims = JwtUtil.parseJWT(token);
            // 获得 userId
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException("token非法...");
        }
        // 从 redis 获得 LoginUser
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
        if (Objects.isNull(loginUser)) {
            // loginUser 为空
            throw new RuntimeException("用户未登录...");
        }
        // 把 user 信息封装给 SecurityContextHolder 以至于后面的程序可以拿到 user 去校验
        // 封装权限信息
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}